package net.gd.servlet;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BaseServlet extends HttpServlet {

	private static final long serialVersionUID = 5701423219862355800L;

	protected void saveError4Ajax(HttpServletRequest req, HttpServletResponse resp, Throwable t) {
		try {
			resp.setStatus(500);
			resp.setContentType("application/Json");
			resp.addHeader("Access-Control-Allow-Origin", "*");
			resp.setCharacterEncoding("utf-8");
			resp.setStatus(HttpServletResponse.SC_OK);
			resp.getWriter().write(t.toString());
			resp.getWriter().flush();
			resp.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	protected void saveError4Ajax(HttpServletRequest req, HttpServletResponse resp, String errorMsg) {
		try {
			resp.setStatus(500);
			resp.setContentType("application/Json");
			resp.addHeader("Access-Control-Allow-Origin", "*");
			resp.setCharacterEncoding("utf-8");
			resp.setStatus(HttpServletResponse.SC_OK);
			resp.getWriter().write(errorMsg);
			resp.getWriter().flush();
			resp.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	protected void saveInfo4Ajax(HttpServletRequest req, HttpServletResponse resp, String result) {
		try {
			resp.setStatus(200);
			resp.setContentType("application/Json");
			resp.addHeader("Access-Control-Allow-Origin", "*");
			resp.setCharacterEncoding("utf-8");
			resp.setStatus(HttpServletResponse.SC_OK);
			resp.getWriter().write(result);
			resp.getWriter().flush();
			resp.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void saveError(HttpServletRequest req, HttpServletResponse resp, Throwable t) {
		req.setAttribute("debugInfo", t.getCause());
	}
	
	protected void saveText4Ajax(HttpServletResponse resp, String text) throws IOException {
	    resp.setCharacterEncoding("utf-8");
	    resp.setContentType("text/plain;charset=utf-8");
	    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(resp.getOutputStream(), "utf-8"));
	    bw.write(text);
	    bw.close();
	}
}
